<template>
  <div class="app-container">
    <el-row style="margin-bottom: 24px">
      <el-col :span="6"
        ><div class="flex flex-column align-center">
          <div class="title">房间总数</div>
          <div class="total">{{ statistics.houseNumber }}间</div>
        </div></el-col
      >
      <el-col :span="6"
        ><div class="flex flex-column align-center left-border">
          <div class="title">已上架总数</div>
          <div class="total">{{ statistics.apartmentStateUpNumber }}间</div>
        </div></el-col
      >
      <el-col :span="6"
        ><div class="flex flex-column align-center right-border">
          <div class="title">未上架总数</div>
          <div class="total">{{ statistics.apartmentStateDownNumber }}间</div>
        </div></el-col
      >
      <el-col :span="6"
        ><div class="flex flex-column align-center">
          <div class="title">未配置</div>
          <div class="total">{{ statistics.editStatusNumber }}间</div>
        </div></el-col
      >
    </el-row>
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
    >
      <el-form-item label="房间名称" prop="estateName">
        <el-input
          v-model="queryParams.estateName"
          placeholder="请输入名称"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="出租周期" prop="apartmenType">
        <el-select
          v-model="queryParams.apartmentType"
          placeholder="请选择"
          clearable
        >
          <el-option
            v-for="dict in dict.type.dict_unsubscribe_rule_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="编辑状态" prop="editStatus">
        <el-select
          v-model="queryParams.editStatus"
          placeholder="请选择"
          clearable
        >
          <el-option
            v-for="dict in dict.type.dict_edit_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="操作人员" prop="updateBy">
        <el-input
          v-model="queryParams.updateBy"
          placeholder="请输入名称"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:role:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>
    <el-row :gutter="10" class="mb8">
      <el-radio-group
        v-model="queryParams.apartmentState"
        @change="handleQuery"
      >
        <el-radio-button :label="undefined"
          >全部（{{ statistics.houseNumber }}）</el-radio-button
        >
        <!-- <el-radio-button label="1">待编辑（123）</el-radio-button> -->
        <el-radio-button label="1"
          >待上架（{{ statistics.apartmentStateDownNumber }}）</el-radio-button
        >
        <el-radio-button label="0"
          >已上架（{{ statistics.apartmentStateUpNumber }}）</el-radio-button
        >
      </el-radio-group>
    </el-row>
    <div class="info">
      <i class="el-icon-info"></i> <span>已选择</span> {{ ids.length }}
      <span>项</span> <label @click="clearSelect" class="clear">清空</label>
    </div>

    <el-table
      v-loading="loading"
      :data="list"
      @selection-change="handleSelectionChange"
      ref="table"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="房间编号" prop="houseId" width="120" />
      <el-table-column
        label="房间"
        prop="roleName"
        :show-overflow-tooltip="true"
        width="150"
      >
        <template slot-scope="scope">
          <span>{{ generateRoom(scope.row) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="地区"
        prop="roleKey"
        :show-overflow-tooltip="true"
        width="150"
      >
        <template slot-scope="scope">
          <span>{{ generateAddress(scope.row) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="出租周期" prop="roleSort" width="100">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.dict_unsubscribe_rule_type"
            :value="scope.row.apartmentType"
          />
        </template>
      </el-table-column>
      <el-table-column label="押金（元）" prop="cashPledge" width="100" />
      <el-table-column label="押付方式" prop="payTypeId" width="100">
        <template slot-scope="scope">
          <span>{{ scope.row.payTypeId | payType(payTypeList,scope.row.apartmentType) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="编辑状态" prop="editStatus" width="100">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.dict_edit_status"
            :value="scope.row.editStatus"
          />
        </template>
      </el-table-column>
      <el-table-column label="上下架" prop="apartmentState" width="100">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.apartmentState"
            active-value="1"
            inactive-value="0"
            @change="handleUnmountStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="编辑人员" prop="updateBy" width="100" />
      <el-table-column
        label="编辑时间"
        align="center"
        prop="updateTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope" v-if="scope.row.roleId !== 1">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['house:allocation:edit']"
            >编辑</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleDetail(scope.row)"
            v-hasPermi="['house:allocation:detail']"
            >详情</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <Edit v-model="open" :title="title" :houseId="id" @success="handleQuery" />
    <!-- 详情弹出层 -->
    <Detail v-model="detailDialogVisible" :title="title" :houseId="id"  />
  </div>
</template>

<script>
import {
  delRole,
  addRole,
  updateRole,
  dataScope,
} from "@/api/system/role";
import {
  listHousingAllocation,
  housingAllocationStatistics,
  listPayType,
  changeApartmentStateStatus,
} from "@/api/house/unmount";
import {
  treeselect as menuTreeselect,
} from "@/api/system/menu";

import Edit from "./components/edit.vue";
import Detail from "./components/detail.vue";

export default {
  name: "Unmount",
  dicts: [
    "sys_normal_disable",
    "dict_unsubscribe_rule_type",
    "dict_apartment_state",
    "dict_edit_status",
  ],
  components: {
    Edit,
    Detail,
  },
  data() {
    return {
      //统计数据
      statistics: {},
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      list: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //表格行id
      id: undefined,
      // 是否显示详情弹出层
      detailDialogVisible: false,
      // 当前选择
      current: "0",
      // 是否显示弹出层（数据权限）
      openDataScope: false,
      menuExpand: false,
      menuNodeAll: false,
      deptExpand: true,
      deptNodeAll: false,
      // 日期范围
      dateRange: [],

      // 菜单列表
      menuOptions: [],
      // 部门列表
      deptOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        estateName: undefined,
        apartmentType: undefined,
        editStatus: undefined,
        apartmentState: undefined,
        updateBy: undefined,
      },
      // 表单参数
      form: {},
      payTypeList: [],
    };
  },
  filters: {
    payType(value, list,type) {
      if(type == 1) return '-'
      let result = list.find((item) => {
        return item.id == value;
      });
      return result ? result.name : value;
    },
  },
  computed: {
    generateRoom() {
      return (row) => {
        let name = "";
        if (row.estateName) name += row.estateName;
        if (row.buildingName) name += row.buildingName + "栋";
        if (row.unitName) name += row.unitName + "单元";
        if (row.roomNumber) name += row.roomNumber + "号";
        return name;
      };
    },
    generateAddress() {
      return (row) => {
        let name = "";
        if (row.provinceName) name += row.provinceName;
        if (row.cityName) name += row.cityName;
        if (row.districtName) name += row.districtName;
        if (row.streetName) name += row.streetName;
        return name;
      };
    },
  },
  created() {
    this.getList();
    this.getHousingAllocationStatistics();
    this.getPayType();
  },
  methods: {
    //获取统计信息
    getHousingAllocationStatistics() {
      housingAllocationStatistics().then((response) => {
        this.statistics = response.data;
      });
    },
    /** 查询角色列表 */
    getList() {
      this.loading = true;
      listHousingAllocation(
        this.addDateRange(this.queryParams, this.dateRange)
      ).then((response) => {
        this.list = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询菜单树结构 */
    getMenuTreeselect() {
      menuTreeselect().then((response) => {
        this.menuOptions = response.data;
      });
    },
    // 所有菜单节点数据
    getMenuAllCheckedKeys() {
      // 目前被选中的菜单节点
      let checkedKeys = this.$refs.menu.getCheckedKeys();
      // 半选中的菜单节点
      let halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys();
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      return checkedKeys;
    },
    // 所有部门节点数据
    getDeptAllCheckedKeys() {
      // 目前被选中的部门节点
      let checkedKeys = this.$refs.dept.getCheckedKeys();
      // 半选中的部门节点
      let halfCheckedKeys = this.$refs.dept.getHalfCheckedKeys();
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      return checkedKeys;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      if (this.$refs.menu != undefined) {
        this.$refs.menu.setCheckedKeys([]);
      }
      (this.menuExpand = false),
        (this.menuNodeAll = false),
        (this.deptExpand = true),
        (this.deptNodeAll = false),
        (this.form = {
          roleId: undefined,
          roleName: undefined,
          roleKey: undefined,
          roleSort: 0,
          status: "0",
          menuIds: [],
          deptIds: [],
          menuCheckStrictly: true,
          deptCheckStrictly: true,
          remark: undefined,
        });
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.houseId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getMenuTreeselect();
      this.open = true;
      this.title = "添加角色";
    },
    handleUpdate(row) {
      this.id = row.houseId
      this.title = "编辑";
      this.open = true;
    },
    handleDetail(row) {
      this.id = row.houseId
      this.title = "详情";
      this.detailDialogVisible = true;

    },
    /** 分配用户操作 */
    handleAuthUser: function (row) {
      const roleId = row.roleId;
      this.$router.push("/system/role-auth/user/" + roleId);
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.roleId != undefined) {
            this.form.menuIds = this.getMenuAllCheckedKeys();
            updateRole(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.form.menuIds = this.getMenuAllCheckedKeys();
            addRole(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 提交按钮（数据权限） */
    submitDataScope: function () {
      if (this.form.roleId != undefined) {
        this.form.deptIds = this.getDeptAllCheckedKeys();
        dataScope(this.form).then((response) => {
          this.$modal.msgSuccess("修改成功");
          this.openDataScope = false;
          this.getList();
        });
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const roleIds = row.roleId || this.ids;
      this.$modal
        .confirm('是否确认删除角色编号为"' + roleIds + '"的数据项？')
        .then(function () {
          return delRole(roleIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "/enterprise/house/housingAllocation/export",
        {
          ...this.queryParams,
          houseIds:this.ids
        },
        `房屋配置信息_${new Date().getTime()}.xlsx`
      );
    },
    //请空选择项
    clearSelect() {
      this.$refs.table.clearSelection();
    },
    //获取押付方式
    getPayType() {
      listPayType().then((response) => {
        this.payTypeList = response.data;
      });
    },
    //修改上下架状态
    handleUnmountStatusChange(row) {
      console.log("apartmentState", row.apartmentState);
      let text = row.apartmentState === "1" ? "上架" : "下架";
      this.$modal
        .confirm('确认要"' + text + '""' + row.houseId + '"房屋配置吗？')
        .then(function () {
          return changeApartmentStateStatus(row.houseId, row.apartmentState);
        })
        .then(() => {
          this.$modal.msgSuccess(text + "成功");
        })
        .catch(function () {
          console.log("err");
          row.apartmentState = row.apartmentState === "1" ? "0" : "1";
        });
    },

  },
};
</script>
<style lang="scss" scoped>
.title {
  font-size: 16px;
  font-weight: bold;
  color: #666;
}
.total {
  font-size: 24px;
  font-weight: 500;
  color: #333;
  margin-top: 6px;
}
.left-border {
  border-left: 1px solid #999;
}
.right-border {
  border-right: 1px solid #999;
}
.info {
  padding: 10px 15px;
  margin: 15px 0;
  background: #e6f7ff;
  color: #1890ff;
  span {
    color: #565c5f;
  }
  .clear {
    margin-left: 20px;
    cursor: pointer;
  }
}
</style>
